package com.dure.hotmemory.scenes;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Bundle;
import android.text.TextUtils;

import com.dure.commonlib.util.AssetsUtil;
import com.dure.commonlib.util.DimentionUtil;
import com.dure.commonlib.util.PathUtil;
import com.dure.commonlib.util.PreferencesUtils;
import com.dure.commonlib.util.ToastUtils;

import com.dure.hotmemory.R;
import com.dure.hotmemory.bean.Bean;
import com.dure.hotmemory.bean.Planet;
import com.dure.hotmemory.controllers.PayController;
import com.dure.hotmemory.drawview.BaseSurfaceView;
import com.dure.hotmemory.listeners.ConfirmListener;
import com.dure.hotmemory.utils.DialogUtil;
import com.fuqianla.paysdk.FuQianLa;
import com.fuqianla.paysdk.FuQianLaPay;
import com.fuqianla.paysdk.bean.FuQianLaResult;

import java.util.ArrayList;


/**
 * Created by leix on 05/11/2016.
 */

public class PayScene extends BaseScene {
    private Paint paint,circlePaint;
    private int lineSize = 5;

    private float mainRadius = 200;
    private Paint textPaint;
    private float textSize = 80;

    private Planet currentPlanet;


    float degreeIncreaseStep = 0.1f;


    double degreeStep;


    boolean dataInited;

    private Bitmap backImg,backPressedImg;
    private int backLeftPadding = 50;
    private int backTopPadding = 50;
    private float backCircleCenterX, backCircleCenterY, backRadius;
    private boolean backPressed;
    private Rect backSrcRect;
    private RectF backDstRect;
    private boolean showBack = true;

    private PayController payController;
    private int topCircleRadius;
    int shadowColor = Color.parseColor("#4C4C4C");
    float[] colorRatio = {0.5f, 1f};
    int[] pressedColors = {Color.parseColor("#989898"), shadowColor};


    public PayScene(BaseSurfaceView baseSurfaceView) {
        super(baseSurfaceView);
        payController = new PayController(this);
        left = baseSurfaceView.getWidth();
        initData();
        initDataFinished = true;
        activity.hideAd();
    }

    @Override
    public void initData() {

        paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(lineSize);
        paint.setStyle(Paint.Style.FILL);

        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(textSize);

        circlePaint = new Paint();
        circlePaint.setColor(Color.WHITE);
        circlePaint.setAntiAlias(true);

        // 添加字体阴影
        textPaint.setShadowLayer(2,3, 3, shadowColor);

    }


    private float connerOrbitRadius;
    private float connerPlanetRadius = 400;

    @Override
    public void handleData() {
        if (!dataInited) {
            currentPlanet = payController.getAllPlanets();
//            backImg = BitmapFactory.decodeStream(AssetsUtil.getAssets(baseSurfaceView.getContext(), "ic_back_arrow_selected.png"));
            backImg = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.back_n);
            backPressedImg = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.back_p);

            topCircleRadius = DimentionUtil.dpToPx(baseSurfaceView.context, 40) / 2;
            backSrcRect = new Rect(0, 0, backImg.getWidth(), backImg.getHeight());
            backLeftPadding = DimentionUtil.dpToPx(baseSurfaceView.context, 10);
            backTopPadding = DimentionUtil.dpToPx(baseSurfaceView.context, 10);

            backCircleCenterX = backLeftPadding + topCircleRadius;
            backCircleCenterY = backTopPadding + topCircleRadius;
            backRadius = topCircleRadius;

            int dstWidth = backImg.getWidth();
            int dstHeight = backImg.getHeight();
            float homeLeft = backCircleCenterX - dstWidth / 2;
            float homeTop = backCircleCenterY - dstHeight / 2;
            backDstRect = new RectF(homeLeft, homeTop, homeLeft + dstWidth, homeTop + dstHeight);

            if (baseSurfaceView.getWidth() > baseSurfaceView.getHeight()) {
                mainRadius = baseSurfaceView.getHeight() / 5;
            } else {
                mainRadius = baseSurfaceView.getWidth() / 5;
            }

            Path path = new Path();
            path.moveTo(0, 0);
            path.lineTo(baseSurfaceView.getWidth() / 2, baseSurfaceView.getHeight() / 2);
            connerOrbitRadius = PathUtil.getPathLength(path);
            connerPlanetRadius = connerOrbitRadius / connerOrbitPlanetRadiusMutiple;


            currentPlanet.radius = connerPlanetRadius / 2;
            currentPlanet.xPosition = baseSurfaceView.getWidth() / 2;
            currentPlanet.yPosition = baseSurfaceView.getHeight() / 2;
            currentPlanet.textSize = baseSurfaceView.getWidth() / 15f;

            dataInited = true;

        }

//        speedControll();
        handleCenterPlanetData();
    }

    private void handleCenterPlanetData() {


        currentPlanet.xPosition += moveSpeed;

        if (!currentPlanet.childPositioned) {
            currentPlanet.childPositioned = true;
            getPlanetPositions(currentPlanet.child_planets);
        }

        handleChildPlanetData();
    }

    private void getPlanetPositions(ArrayList<Planet> planetList) {
        int planetNumber = currentPlanet.child_planets.size();
        if (planetNumber <= 0) {
            return;
        }

        double degree = 360 / planetNumber;
        for (int i = 0; i < planetNumber; i++) {
            Planet planet = currentPlanet.child_planets.get(i);
            planet.degree = degree * i;
            planet.radius = currentPlanet.radius / 2;
            planet.textSize = currentPlanet.textSize / 2;
        }
    }

    float connerOrbitPlanetRadiusMutiple = 2.5f;
    float centerOrbitPlanetRadiusMutiple = 1.75f;

    private void handleChildPlanetData() {
        for (int i = 0; i < currentPlanet.child_planets.size(); i++) {
            Planet planet = currentPlanet.child_planets.get(i);
            double arc = planet.degree * 2 * Math.PI / 360;

            float xPosition = (float) ((centerOrbitPlanetRadiusMutiple * currentPlanet.radius) * Math.cos(arc) + currentPlanet.xPosition);
            float yPosition = (float) ((centerOrbitPlanetRadiusMutiple * currentPlanet.radius) * Math.sin(arc) + currentPlanet.yPosition);
            planet.xPosition = xPosition;
            planet.yPosition = yPosition;

            // 让星球转运起来
            moveChildPlanet(planet);


            planet.parent_planet = currentPlanet;

        }
    }

    private void moveChildPlanet(Planet planet) {
        if (degreeStep == 0)
            planet.degree += degreeIncreaseStep;
        else {
            planet.degree += degreeStep;
        }
        if (planet.degree > 360) {
            planet.degree = planet.degree - 360;
        }
    }

    @Override
    public void handleDraw(Canvas canvas) {
        if (dataInited)
            drawCenterPlanet(canvas);

        if (showBack && dataInited) {

            paint.setStrokeWidth(lineSize);
            paint.setStyle(Paint.Style.FILL);
            RectF dstRect = new RectF(backDstRect.left + left, backDstRect.top, backDstRect.right + left, backDstRect.bottom);

            float shadowStartX = backCircleCenterX + (float) (backRadius * 0.6 * Math.cos(Math.toRadians(135)));
            float shadowStartY = backCircleCenterY - (float) (backRadius * 0.6 * Math.sin(Math.toRadians(135)));

            if (backPressed) {
                if (backRadius > 0){
                    RadialGradient radialGradient = new RadialGradient(shadowStartX + left, shadowStartY, 2 * backRadius,
                            pressedColors, colorRatio, Shader.TileMode.CLAMP);
                    paint.setShader(radialGradient);
                }

                canvas.drawCircle(backCircleCenterX + left, backCircleCenterY, backRadius, paint);
                canvas.drawBitmap(backPressedImg, backSrcRect, dstRect, null);
            } else {
                if (backRadius > 0){
                    RadialGradient radialGradient = new RadialGradient(shadowStartX + left, shadowStartY, 2 * backRadius,
                            new int[]{Color.WHITE, shadowColor}, colorRatio, Shader.TileMode.CLAMP);
                    paint.setShader(radialGradient);
                }

                canvas.drawCircle(backCircleCenterX + left, backCircleCenterY, backRadius, paint);
                canvas.drawBitmap(backImg, backSrcRect, dstRect, null);
            }
        }
    }

    private void drawCenterPlanet(Canvas canvas) {
        textPaint.setTextSize(currentPlanet.textSize);
        textPaint.setColor(Color.parseColor(currentPlanet.text_color));
        paint.setColor(Color.parseColor(currentPlanet.planet_color));

        // 绘制中间的planet
        drawPlanet(canvas, currentPlanet, textPaint, paint);

        circlePaint.setStyle(Paint.Style.STROKE);
        circlePaint.setColor(Color.YELLOW);
        circlePaint.setStrokeWidth(5);
        circlePaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.OUTER));
        canvas.drawCircle(currentPlanet.xPosition + left, currentPlanet.yPosition,
                currentPlanet.radius * centerOrbitPlanetRadiusMutiple, circlePaint);


        if (currentPlanet.child_planets != null && currentPlanet.child_planets.size() > 0)
            drawChildPlanets(canvas);
    }

    private void drawChildPlanets(Canvas canvas) {

        for (int i = 0; i < currentPlanet.child_planets.size(); i++) {
            Planet planet = currentPlanet.child_planets.get(i);
            planet.textSize = currentPlanet.textSize / 2;
            planet.radius = currentPlanet.radius / 2;

            textPaint.setTextSize(planet.textSize);
            textPaint.setColor(Color.parseColor(planet.text_color));
            if (!TextUtils.isEmpty(planet.introduce)) {// 用于判断是否开通支付功能
                if (planet.pressed) {
                    paint.setColor(Color.parseColor(planet.pressed_color));
                } else {
                    paint.setColor(Color.parseColor(planet.planet_color));
                }
                drawPlanet(canvas, planet, textPaint, paint);
            } else {// 未开通支付功能
                paint.setColor(Color.GRAY);
                drawPlanet(canvas, planet,  textPaint, paint);
            }
        }

    }


    private void drawPlanet(Canvas canvas, Planet planet,  Paint textPaint, Paint paint) {

        float shadowStartX = planet.xPosition + (float) (planet.radius * 0.3 * Math.cos(Math.toRadians(135)));
        float shadowStartY = planet.yPosition - (float) (planet.radius * 0.3 * Math.sin(Math.toRadians(135)));

        int showColor = Color.parseColor(planet.planet_color);
        if (planet.pressed){
            showColor = Color.parseColor(planet.pressed_color);
        }
        if (planet.radius > 0){
            RadialGradient lg = new RadialGradient(shadowStartX + left, shadowStartY, 1.8f * planet.radius,
                    new int[]{showColor,shadowColor}, colorRatio, Shader.TileMode.CLAMP);
            paint.setShader(lg);
        }

        canvas.drawCircle(planet.xPosition + left, planet.yPosition, planet.radius, paint);

        canvas.drawText(planet.planet, planet.xPosition - textPaint.measureText(planet.planet) / 2 + left,
                planet.yPosition + textPaint.getTextSize() / 2, textPaint);

        paint.setMaskFilter(null);


    }

    @Override
    public void handleDown(PointF pointF) {
        if (pointF == null)
            return;
        containPoint(pointF.x, pointF.y);
    }

    Planet clickedPlanet;

    @Override
    public void handleUp(PointF pointF) {
        if (backPressed) {// 判断是否点击了返回
            backPressed = false;
            payController.handler.sendEmptyMessage(0);
        } else {// 判断是否点击了child planet
            if (clickedPlanet != null && clickedPlanet.pressed) {
                clickedPlanet.pressed = false;

                if (!TextUtils.isEmpty(clickedPlanet.introduce)) {
                    if (TextUtils.isEmpty(payType)) {
                        clickedPlanet = null;
                        return;
                    } else if (!TextUtils.equals(payType, "reward")) {
                        if (PreferencesUtils.getBoolean(activity, "login_success")) {
                            payController.goToPay(clickedPlanet, payType, amount);
                        }else{
                            ToastUtils.show(baseSurfaceView.context, "请先登录");
                            clickedPlanet = null;
                            return;
                        }
                    }else{// 打赏不需要判断条件
                        payController.goToPay(clickedPlanet, payType, amount);
                        clickedPlanet = null;
                    }

                } else {
                    payController.handler.sendEmptyMessage(1);
                    clickedPlanet = null;
                }

            }
        }
    }

    public Planet getClickedPlanet() {
        return clickedPlanet;
    }

    public String getPayType() {
        return payType;
    }

    public double getAmount() {
        return amount;
    }

    private void containPoint(float x, float y) {

        if (showBack) {
            RectF rectF = new RectF();
            Path path = new Path();
            path.addCircle(backCircleCenterX, backCircleCenterY, backRadius, Path.Direction.CCW);
            path.computeBounds(rectF, true);
            if (rectF.contains(x, y)) {// 判断是否点返回图标
                backPressed = true;
                return;
            } else {
                backPressed = false;
            }
        }

        for (int i = 0; i < currentPlanet.child_planets.size(); i++) {
            Planet planet = currentPlanet.child_planets.get(i);

            double arc = planet.degree * 2 * Math.PI / 360;
            int centerX = (int) (2 * mainRadius * Math.cos(arc) + baseSurfaceView.getWidth() / 2);
            int centerY = (int) (2 * mainRadius * Math.sin(arc) + baseSurfaceView.getHeight() / 2);

            RectF rectF = new RectF();
            Path path = new Path();

            path.addCircle(centerX, centerY, mainRadius / 2, Path.Direction.CCW);
            path.computeBounds(rectF, true);

            if (rectF.contains(x, y)) {
                clickedPlanet = planet;
                clickedPlanet.pressed = true;
                planet.parent_planet = currentPlanet;


                break;
            }

        }
    }

    private boolean payStarted;
    private FuQianLaPay pay;

    private String payType;
    private double amount;

    public void setPayType(String payType) {
        this.payType = payType;
    }

    public void setAmount(double amount) {
//        amount = 0.01;
        this.amount = amount;

    }

    @Override
    public void handleRequestSuccess(Bean bean) {
        payController.handleRequestSuccess(bean);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //返回支付结果
        if (requestCode == FuQianLa.REQUESTCODE
                && resultCode == FuQianLa.RESULTCODE
                && data != null) {
            FuQianLaResult result = data.getParcelableExtra(FuQianLa.PAYRESULT_KEY);

            if (TextUtils.equals(result.payCode, "9000")) {
                if (!TextUtils.equals(payType, "reward")) {
                    payController.addPayUser(amount);

                    PreferencesUtils.putBoolean(activity, "paied", true);
                    DialogUtil.showSimpleDialog(activity, "支付成功", new ConfirmListener() {
                        @Override
                        public void confirmed(Bundle bundle) {
                            activity.onBackPressed();
                        }
                    });
                } else {
                    DialogUtil.showSimpleDialog(activity, "感谢您的打赏， 祝你早日学有所成！", new ConfirmListener() {
                        @Override
                        public void confirmed(Bundle bundle) {
                            activity.onBackPressed();
                        }
                    });
                }
            } else {
                DialogUtil.showSimpleDialog(activity, "支付失败", null);
            }
            payStarted = false;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    public void setPayStarted(boolean payStarted) {
        this.payStarted = payStarted;
    }

    public boolean isPayStarted() {
        return payStarted;
    }
}
